<template>
  <!-- 新增、编辑纪检人员 -->
  <base-breadcrumb class="UpdatePersonManage-container" :state="breadcrumbState">
    <a-spin :spinning="loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="人员信息" />
        <custom-form ref="ruleForm" :isValidate="true" :editModel="isDisabled ? 'V' : ''" :rules="rules"
          :form="formInfo" :formList="formItemList" @onSelectChange="handleSelectPerson"
          @changeName="handleChangeBranchName">
          <template v-slot:content>
            <div class="slot-wrapper">
              <title-name title="主要工作经验" />
              <a-form-model-item prop="content" class="ant-form-item--full requiredFormItem">
                <BaseTextarea :disabled="isDisabled" v-model="formInfo.content" />
              </a-form-model-item>
            </div>
          </template>
        </custom-form>
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button v-if="!isDisabled" type="primary" :loading="loadingState.isSubmit" @click="handleSubmit">提交</a-button>
        <a-button class="ml12" type="primary" @click="handleClose">关闭</a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import Selector from '@/components/Select/Selector'
import SelectUnit from '@/components/Select/SelectUnit'
import SelectOrgPeople from '@/components/Select/SelectOrgPeople'
import { addPerson, updatePerson, getPersonDetail } from '@/api/disciplineInspection/orgStructure/index.js'
import { getUsersDetail } from '@/api/commons'

export default {
  name: 'a' + Date.now(),
  data() {
    return {
      loadingState: {
        isDetail: false,
        isSubmit: false,
      },
      formInfo: {},
      rules: {
        levelId: [{ required: true, message: '请选择所属层级', trigger: 'change' }],
        branchOrgId: [{ required: true, message: '请选择单位', trigger: 'change' }],
        userId: [{ required: true, message: '请选择', trigger: 'change' }],
        checkTime: [{ required: true, message: '请选择入职纪检时间', trigger: 'change' }],
        content: [{ required: true, message: '请输入主要工作经验', trigger: 'blur' }],
      },
    }
  },
  computed: {
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    breadcrumbState() {
      const map = {
        add: 1,
        edit: 2,
        look: 3,
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        // {
        //   label: '所属层级',
        //   keyName: 'levelId',
        //   viewName: 'levelName',
        //   type: Selector,
        //   disabled: this.isDisabled,
        //   attrs: {
        //     selectType: '1',
        //     urlType: 'union',
        //     filterFn: (item) => {
        //       return this.$route.query.levelName !== '项目' && item.code !== 'PD' || this.$route.query.levelName === '项目'
        //     },
        //   },
        // },
        // {
        //   label: '单位',
        //   keyName: 'branchOrgId',
        //   viewName: 'branchOrgName',
        //   type: SelectUnit,
        //   disabled: this.isDisabled,
        //   attrs: {
        //     ref: 'selectUnit',
        //     mode: 'default',
        //     useAll: true,
        //     form: this.formInfo,
        //     keyValue: 'levelId',
        //     isEdit: this.pageType !== 'look',
        //   },
        // },
        {
          label: '公司/分公司',
          keyName: 'branchOrgId',
          viewName: 'branchOrgName',
          type: SelectUnit,
          disabled: this.isDisabled,
          attrs: {
            ref: 'selectUnit',
            mode: 'default',
            useAll: true,
            isCorrCompany: true,
            isEdit: this.pageType !== 'look',
            linkage: true
          },
        },
        {
          label: '姓名',
          keyName: 'userId',
          viewName: 'name',
          type: SelectOrgPeople,
          disabled: this.isDisabled,
          attrs: {
            validEmpty: true,
            valueKey: 'userId',
            orgId: this.formInfo.branchOrgId,
          },
        },
        {
          label: '手机号码',
          keyName: 'phone',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '身份证号码',
          keyName: 'idcard',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '性别',
          keyName: 'sex',
          type: 'a-select',
          data: [
            {
              label: '男',
              value: '1',
            },
            {
              label: '女',
              value: '0',
            },
          ],
          disabled: true
        },
        {
          label: '政治面貌',
          keyName: 'ploicy',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '民族',
          keyName: 'ploicy1',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '最高学历',
          keyName: 'specialitieMax',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '所学专业',
          keyName: 'specialitie',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '职称',
          keyName: 'jobTitle',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '岗位职务',
          keyName: 'postName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '入职纪检时间',
          keyName: 'checkTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          },
        },
        {
          slot: true,
          keyName: 'content',
          customItemSlot: true,
          span: 24,
        },
      ]
    },
  },
  created() {
    this.getPersonDetailReq()
  },
  methods: {
    /**
     * 用户详情
     */
    async getUsersDetailReq(id) {
      if (!id) return
      try {
        const res = await getUsersDetail({ userId: id })
        const sexMap = {
          0: '女',
          1: '男',
        }
        const { idCard, sex, specialitieMax, specialitie, jobTitle } = res.data
        this.formInfo = {
          ...this.formInfo,
          idcard: idCard,
          sex: sexMap[sex] || '',
          specialitieMax,
          specialitie,
          jobTitle,
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getPersonDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id,
        }
        this.loadingState.isDetail = true
        const res = await getPersonDetail(params)
        this.loadingState.isDetail = false
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
        }
        this.$nextTick(() => {
          this.formInfo.branchOrgId = res.data.branchOrgId
        })
        this.getUsersDetailReq(this.formInfo.userId)
      } catch (e) {
        this.loadingState.isDetail = false
        console.error(e)
      }
    },
    /**
     * 单位名称改变
     * @param {String} key 改变的表单键名
     * @param {String} val 改变后的name值
     */
    handleChangeBranchName(key, val = '') {
      if (key === 'branchOrgId') {
        this.formInfo.branchOrgName = val
      }
    },
    /**
     * 人员选择
     * @param {String} key 改变的表单键名
     * @param {Object} data 选中人员的信息对象
     */
    handleSelectPerson(key, data = {}) {
      if (key === 'userId') {
        const { name, phoneNum, idCard, sex, specialitieMax, specialitie, jobTitle, postPNames } = data
        this.formInfo = {
          ...this.formInfo,
          name,
          phone: phoneNum,
          idcard: idCard,
          sex,
          specialitieMax,
          specialitie,
          jobTitle,
          postName: (postPNames && postPNames.join(',')) || '',
        }
      }
    },
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message.warning("请填写完所有必填项信息")
          return
        }
        this.invokeSave()
      })
    },
    async invokeSave() {
      if (this.loadingState.isSubmit) return
      this.loadingState.isSubmit = true
      try {
        const params = {
          ...this.formInfo,
          id: this.$route.query.id || void 0,
          levelId: this.formInfo.branchOrgId === '53085e2c9f1f4685801ef31994f57c49' ? '605004340528287745' : '605004401341501446'
        }
        const fn = this.pageType === 'add' ? addPerson : updatePerson
        await fn(params)
        this.$message.success('提交成功')
        this.$multiTab.close()
      } catch (e) {
        console.error(e)
      } finally {
        this.loadingState.isSubmit = false
      }
    },
    handleClose() {
      this.$close()
    },
  },
}
</script>

<style lang="less" scoped>
.slot-wrapper {
  padding-top: 50px;
}
</style>
